package com.example.testapp.activity.activity.study;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.testapp.R;
import com.example.testapp.activity.activity.SuperActivity;
import com.example.testapp.activity.http.AsyncHttpUtil;
import com.example.testapp.activity.http.Contacts;
import com.example.testapp.activity.model.GameItem;
import com.example.testapp.activity.util.JsonUtils;
import com.example.testapp.activity.view.ErrorHintView;
import com.example.testapp.activity.view.listview.PullToRefreshBase;
import com.example.testapp.activity.view.listview.PullToRefreshListView;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.squareup.picasso.Picasso;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import cz.msebera.android.httpclient.Header;

/**
 * Created by l on 2016/9/1.
 */
public class GamesLifeActivity extends SuperActivity {

    private PullToRefreshListView mGamesListView;
    private ErrorHintView   mHintView;

    private List<GameItem> mList = new ArrayList<>();
    private GameListAdapter  mAdapter;

    public static int VIEW_LIST = 1;
    /**显示断网**/
    public static int VIEW_WIFIFAILUER = 2;
    /** 显示加载数据失败 **/
    public static int VIEW_LOADFAILURE = 3;
    public static int VIEW_LOADING = 4;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_games_life);
        getWindow().setBackgroundDrawable(null);
        initView();
    }

    private void initView() {
        RelativeLayout headView = (RelativeLayout) this.findViewById(R.id.head);
        headView.findViewById(R.id.back_left).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        TextView title = (TextView) headView.findViewById(R.id.head_title);
        title.setText("最新火爆游戏");

        mGamesListView = (PullToRefreshListView) this.findViewById(R.id.games_list);
        mHintView = (ErrorHintView) this.findViewById(R.id.games_hintview);

        setUpListener();
        showLoading(VIEW_LOADING);
        loadGameInfo(true);
    }

    private void setUpListener() {
       mAdapter = new GameListAdapter();
       mGamesListView.setAdapter(mAdapter);
       mGamesListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
           @Override
           public void onRefresh(PullToRefreshBase<ListView> refreshView) {
               if (refreshView.isHeaderShown()){
                   loadGameInfo(true);
               }
           }
       });

       mGamesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
           @Override
           public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
               GameItem gameItem = mList.get(position - 1);
               Intent intent = new Intent(mContext, GameDetailActivity.class);
               intent.putExtra("ztid",gameItem.getZtid());
               intent.putExtra("ztname", gameItem.getZtname());
               mContext.startActivity(intent);
           }
       });
    }

    private void showLoading(int i) {
        mGamesListView.setVisibility(View.GONE);
        mHintView.setVisibility(View.GONE);

        switch (i){
            case 1:
                mHintView.hideLoading();
                mGamesListView.setVisibility(View.VISIBLE);
                break;
            case 2:
                mHintView.hideLoading();
                mHintView.netError(new ErrorHintView.OperateListener() {
                    @Override
                    public void operate() {
                        showLoading(VIEW_LOADING);
                        loadGameInfo(true);
                    }
                });
                break;
            case 3:
                mHintView.hideLoading();
                mHintView.loadFailure(new ErrorHintView.OperateListener() {
                    @Override
                    public void operate() {
                        showLoading(VIEW_LOADING);
                        loadGameInfo(true);
                    }
                });
                break;
            case 4:
                mHintView.loadingdata();
                break;
        }
    }

    private void loadGameInfo(final boolean show) {
        AsyncHttpUtil.get(Contacts.GAMES_PATH, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                 mGamesListView.onRefreshComplete();

                try {
                   if (responseBody != null && responseBody.length > 0){
                       JSONObject object = new JSONObject(new String(responseBody));
                       JSONArray array = object.getJSONArray("items");
                       if (array != null){
                           List<GameItem> items = JsonUtils.getInstance(GameItem.class, array);
                           if (items != null && items.size() > 0){
                               if (show){
                                   mList.clear();
                               }
                               mList.addAll(items);
                               showLoading(VIEW_LIST);
                               mAdapter.notifyDataSetChanged();
                           }else{
                               showLoading(VIEW_LOADFAILURE);
                           }
                       }else{
                           showLoading(VIEW_LOADFAILURE);
                       }
                   }
                }catch (Exception e){
                    e.printStackTrace();
                    showLoading(VIEW_LOADFAILURE);
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
               showLoading(VIEW_WIFIFAILUER);
            }
        });
    }

    public class GameListAdapter extends BaseAdapter{

        @Override
        public int getCount() {
            return mList.size();
        }

        @Override
        public Object getItem(int position) {
            return mList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null){
                holder = new ViewHolder();
                convertView = View.inflate(mContext, R.layout.view_item_games_lv, null);
                holder.img = (ImageView) convertView.findViewById(R.id.img);
                holder.text = (TextView) convertView.findViewById(R.id.text);
                convertView.setTag(holder);
            }else{
                holder = (ViewHolder) convertView.getTag();
            }

            GameItem items = mList.get(position);

            if (!TextUtils.isEmpty(items.getZtimg())){
                Picasso.with(mContext).load(Contacts.GAMES_ITEM_PATH + items.getZtimg()).placeholder(R.color.ECECEC).error(R.color.ECECEC).into(holder.img);
            }
            if (!TextUtils.isEmpty(items.getZtname())){
                holder.text.setText(items.getZtname());
            }else{
                holder.text.setText("");
            }
            return convertView;
        }

        public class ViewHolder{
            ImageView img;
            TextView text;
        }
    }

    @Override
    protected void obtainInfo() {

    }
}
